package com.jf3q.front.controller;

import com.aliyun.teautil.Common;
import com.aliyun.vod20170321.models.GetVideoPlayAuthResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jf3q.common.domain.EduChapter;
import com.jf3q.common.domain.EduCourse;
import com.jf3q.common.domain.EduSubject;
import com.jf3q.common.domain.EduVideo;
import com.jf3q.common.elatic.entity.CourseEntity;
import com.jf3q.common.mapper.EduCourseDescriptionMapper;
import com.jf3q.common.sample.Sample;
import com.jf3q.common.vo.CourseWebVo;
import com.jf3q.common.vo.ResultVo;
import com.jf3q.front.dto.SearchCourse;
import com.jf3q.front.service.impl.*;
import com.jf3q.front.vo.CoursePage;
import io.swagger.v3.oas.annotations.Operation;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author ASUS
 * @date 2024/5/30
 * @apiNote
 */
@RestController
@RequestMapping("/course")
public class CourseController {

    @Autowired
    CourseServiceImpl courseService;

    @Autowired
    ChapterServiceImpl chapterService;

    @Autowired
    VideoServiceImpl videoService;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    EduCourseDescriptionMapper courseDescriptionMapper;

    @Autowired
    EduCommentServiceImpl commentService;


    @Autowired
    Sample sample;


    @GetMapping("/newCourse")
    public ResultVo newCourse(){
        List<EduCourse> newCourse ;
        if (!redisTemplate.hasKey("newCourse")){
            Page<EduCourse> page = courseService.page(
                    new Page<>(1, 4),
                    new LambdaQueryWrapper<EduCourse>().orderByDesc(EduCourse::getEduCreate));
            redisTemplate.opsForList().leftPushAll("newCourse",page.getRecords());
            redisTemplate.expire("newCourse",1, TimeUnit.HOURS);
            newCourse=page.getRecords();
        }else {
            newCourse= redisTemplate.opsForList().range("newCourse",0,-1);
        }
        return ResultVo.success("最新门课程",newCourse);
    }

    @GetMapping("/detail/{id}")
    public ResultVo detail(@PathVariable String id){
        CourseWebVo courseWebVo = courseService.detailById(id);


        List<EduChapter> list = chapterService.list(
                new LambdaQueryWrapper<EduChapter>()
                        .eq(EduChapter::getCourseId, id)
                        .orderByAsc(EduChapter::getSort));
        for (EduChapter chapter : list) {
            chapter.setVideos(videoService.list(
                    new LambdaQueryWrapper<EduVideo>()
                            .eq(EduVideo::getChapterId, chapter.getId())
                            .orderByAsc(EduVideo::getSort)));
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("courseWebVo",courseWebVo);
        map.put("chapterVideoList",list);
        map.put("isBuy",false );
        return ResultVo.success(map);
    }

    @GetMapping("/listByTeacherId/{id}")
    public ResultVo listByTeacherId(@PathVariable String id){
        List<EduCourse> list = courseService.list(new LambdaQueryWrapper<EduCourse>().eq(EduCourse::getTeacherId, id));
        return ResultVo.success(list);
    }


    @GetMapping("/getPlayAuth/{id}")
    public ResultVo getPlayAuth(@PathVariable String id) throws Exception {
        com.aliyun.vod20170321.Client client = sample.createClient();
        com.aliyun.vod20170321.models.GetVideoPlayAuthRequest getVideoPlayAuthRequest = new com.aliyun.vod20170321.models.GetVideoPlayAuthRequest()
                .setVideoId(id);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            GetVideoPlayAuthResponse response = client.getVideoPlayAuthWithOptions(getVideoPlayAuthRequest, runtime);
            com.aliyun.teaconsole.Client.log(Common.toJSONString(response));

            return ResultVo.success(response.getBody().getPlayAuth());
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return ResultVo.error(e.getMessage());
        }
    }

    @Autowired
    SubjectServiceImpl subjectService;

    @GetMapping("/getAllSubject")
    public ResultVo getAllSubject() {
        List<EduSubject> list = subjectService.list();
        List<EduSubject> tree = new ArrayList<>();
        for (EduSubject subject : list) {
            if (subject.getParentId().equals("0")) {
                for (EduSubject subject1 : list) {
                    if (subject1.getParentId().equals(subject.getId())) {
                        subject.getSubjects().add(subject1);
                    }
                }
                tree.add(subject);
            }
        }
        return ResultVo.success(tree);
    }

    @PostMapping("/getFrontCourseList/{pageNum}/{pageSize}")
    public ResultVo getFrontCourseList(@PathVariable Integer pageNum,
                                       @PathVariable Integer pageSize,
                                       @RequestBody SearchCourse searchCourse){
        LambdaQueryWrapper<EduCourse> wrapper = new LambdaQueryWrapper<>();
        if (!ObjectUtils.isEmpty(searchCourse)){
            if (!ObjectUtils.isEmpty(searchCourse.getCourseName())){
                wrapper.like(EduCourse::getTitle,searchCourse.getCourseName());
            }
            if (!ObjectUtils.isEmpty(searchCourse.getSubjectParentId())){
                wrapper.eq(EduCourse::getSubjectParentId,searchCourse.getSubjectParentId());
            }
            if (!ObjectUtils.isEmpty(searchCourse.getSubjectId())){
                wrapper.eq(EduCourse::getSubjectId,searchCourse.getSubjectId());
            }
            if (!ObjectUtils.isEmpty(searchCourse.getBuyCountSort())){
                wrapper.orderByDesc(EduCourse::getBuyCount);
            } else if (!ObjectUtils.isEmpty(searchCourse.getGmtCreateSort())){
                wrapper.orderByDesc(EduCourse::getEduCreate);
            } else if (!ObjectUtils.isEmpty(searchCourse.getPriceSort())){
                wrapper.orderByDesc(EduCourse::getPrice);
            }
        }
        Page<EduCourse> page = courseService.page(new Page<>(pageNum, pageSize), wrapper);
        CoursePage data = new CoursePage();
        data.setItems(page.getRecords());
        data.setTotal((int) page.getTotal());
        data.setPages((int) page.getPages());
        data.setCurrent((int) page.getCurrent());
        data.setHasPrevious(page.hasPrevious());
        data.setHasNext(page.hasNext());
        return ResultVo.success(data);
    }

    @Autowired
    CourseEntityService courseEntityService;


    //根据关键词全文检索-高亮显示
    @GetMapping("/search")
    @Operation(summary = "根据关键词全文检索-高亮显示")
    public ResultVo searchCourses(String keyword,
                                  @RequestParam(defaultValue = "1") Integer number,
                                  @RequestParam(defaultValue = "4")Integer size) {
        org.springframework.data.domain.Page<CourseEntity> courseEntities = courseEntityService.searchByKeyword(keyword, number, size);
        return setResultMap(size, courseEntities);
    }

    @NotNull
    private ResultVo setResultMap(@RequestParam(defaultValue = "4") Integer size, org.springframework.data.domain.Page<CourseEntity> courseEntities) {
        Map<String, Object> map = new HashMap<>();
        map.put("items", courseEntities.getContent());
        map.put("current", courseEntities.getNumber()+1);
        map.put("pages", courseEntities.getTotalPages());
        map.put("size", size);
        map.put("total", courseEntities.getTotalElements());
        map.put("hasNext", courseEntities.hasNext());
        map.put("hasPrevious", courseEntities.hasPrevious());

        return  ResultVo.success(map);
    }

    @PostMapping("/search/subject")
    @Operation(summary = "分类查询课程")
    public ResultVo searchBySubject(@RequestBody SearchCourse dto,
                                    @RequestParam(defaultValue = "1") Integer number,
                                    @RequestParam(defaultValue = "4")Integer size) {
        //把分页数据获取出来，放到map集合
        org.springframework.data.domain.Page<CourseEntity> courseEntities = courseEntityService.searchBySubject(dto, number, size);
        return setResultMap(number, courseEntities);
    }


    //List<EduCourse> list = courseService.list();
    //    for (EduCourse course : list) {
    //    CourseEntity courseEntity= new CourseEntity();
    //    BeanUtils.copyProperties(course,courseEntity);
    //    courseEntity.setDescription(courseDescriptionMapper.selectById(course.getId()).getDescription());
    //    courseEntity.setSubjectName(subjectService.getById(course.getSubjectId()).getTitle());
    //    courseEntity.setSubjectParentName(subjectService.getById(course.getSubjectParentId()).getTitle());
    //    courseEntityService.addCourse(courseEntity);
    //}
}
